from spargameproject.spargame.game.engine.game_engine import PlayHandler
from spargameproject.spargame.models import GamePlayer

class UndryHandler(PlayHandler):
  def getType(self):
    return 'undry'

  def handlePlay(self, play, game_engine):
    card_indeces_str = play.getMetadata('card_indeces')
    if not card_indeces_str:
      return ['Please select one or more cards'], {}
    card_indeces = [int(x) for x in card_indeces_str.split(",")]
    game_player = GamePlayer.objects.get(game=play.game, player=play.player)
    session = play.game.getMetadata('session')
    hand = game_player.getMetadata('hand')[session]
    dry_card_indeces = game_player.getMetadata('dry_card_indeces')
    current_cards_left = game_player.getMetadata('current_cards_left')
    cards_left = game_player.getMetadata('cards_left')

    response, errors = {}, []
    response['card_numbers'] = str(5 - len(dry_card_indeces))
    for card_index in card_indeces:
      if not card_index in dry_card_indeces:
        return ['Attempting to undry a card that is not dried'], {}
      cards_left[card_index] = hand[card_index]
      current_cards_left.append(hand[card_index])
    dry_card_indeces = [x for x in dry_card_indeces if not x in card_indeces]

    game_player.setMetadataWithMap({
        'dry_card_indeces': dry_card_indeces,
        'current_cards_left': current_cards_left,
        'cards_left': cards_left})

    # Build the display message and update cards_left.
    message = 'Undried %s card%s' % (len(card_indeces), 's' if len(card_indeces) > 1 else '')
    play.setMetadata('message', message)
    response['message'] = message

    return errors, response
